package org.net5ijy.commons.http.response;

import static org.net5ijy.commons.http.constants.HttpHeaders.HEADER_SET_COOKIE;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * ResponseHolder类
 *
 * @author xuguofeng
 * @date 2020/7/13 12:10
 */
public class ResponseHolder {

  private int statusCode;

  private String contentType;

  private Map<String, HttpHeader> httpHeaderMap = new HashMap<>(8);

  private List<HttpHeader> headers = new ArrayList<>();

  private Map<String, Cookie> cookies = new HashMap<>(4);

  public void setStatusCode(int statusCode) {
    this.statusCode = statusCode;
  }

  public void setContentType(String contentType) {
    this.contentType = contentType;
  }

  public int getStatusCode() {
    return statusCode;
  }

  public String getContentType() {
    return contentType == null ? "" : contentType;
  }

  public List<HttpHeader> getHeaders() {
    return headers;
  }

  public Map<String, Cookie> getCookies() {
    return cookies;
  }

  public void addHeader(String name, String value) {
    HttpHeader httpHeader = new HttpHeader(name, value);
    this.httpHeaderMap.put(name, httpHeader);
    this.headers.add(httpHeader);
    this.addCookie(httpHeader);
  }

  public String headerValue(String name) {
    HttpHeader httpHeader = this.httpHeaderMap.get(name);
    if (httpHeader == null) {
      return null;
    }
    return httpHeader.value;
  }

  public String cookieValue(String name) {
    return this.cookies.get(name).value;
  }

  private void addCookie(HttpHeader header) {
    String name = header.getName();
    if (HEADER_SET_COOKIE.equals(name)) {
      String value = header.getValue();
      String[] vs = value.split(";\\s");
      for (String v : vs) {
        String[] ss = v.split("=");
        if (ss.length == 2) {
          cookies.put(ss[0], new Cookie(ss[0], ss[1]));
        }
      }
    }
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  public static class Cookie {

    private String name;

    private String value;
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  public static class HttpHeader {

    private String name;

    private String value;
  }
}
